package com.espirit.eap.relationship;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Session;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.googlecode.cswish.struts.spring.GenericService;
import com.googlecode.cswish.struts.spring.ObjectFactory;
@Service
public class PartyService {
	@Resource
	private GenericService genericService;
	
	@Resource
	private ObjectFactory objectFactory;
	
	@Resource
	PartyRelationshipService partyRelationshipService;
	
	
	@PersistenceContext(unitName="espirit")
	private EntityManager em;
	
	@Transactional(propagation=Propagation.REQUIRES_NEW)
	public <T> void add(T model){
		genericService.add(model);
	}
	
	@Transactional(propagation=Propagation.REQUIRES_NEW)
	public <T> void update(T model){
		genericService.update(model);
	}
	
	
	@SuppressWarnings("unchecked")
	public <T extends Party> T getPartyByName(String name,Class<T> clazz){
		Party party = (Party)objectFactory.buildModel(clazz.getName(),null);
		party.setName(name);
		return (T)getParty(party);
	}

	public <T extends Party> T getParty(T party){
		return genericService.searchAll(party).getData(0);
	}
	
	public <T extends Party> void add(T party) {
		String partyTypeName = party.getClass().getSimpleName();
		PartyType partyType = new PartyType();
		partyType.setName(partyTypeName);
		PartyType existed = genericService.searchAll(partyType).getData(0);
		if (existed != null) {
			party.setPartyType(existed);
		} else {
			partyType = genericService.add(partyType);
		}
		genericService.add(party);
	}
	
	public void cleanPartyRelationship(Integer dbPartyId){
		String hql = "delete from PartyRelationship where partyChild.id = " + dbPartyId;
		int results = ((Session)em.getDelegate()).createQuery(hql).executeUpdate();
	}
	
	public void setPartyRelaionship(Party child, String parentIds ){
    	if (!StringUtils.isEmpty(parentIds)) {
			String[] ids = StringUtils.split(parentIds, ',');
			if (ids != null){
				for (String theId : ids) {
					Party parent = new Party();
					parent.setId(new Integer(theId));
					parent = genericService.load(parent);
					PartyRelationship prs = parent.addChildParty(child);
					genericService.add(prs);
				}
			}
		}
	}
}
